#include "OpenTissueInstance.h"
#include <OpenTissueThread.h>
OpenTissueInstance* OpenTissueInstance::_instance = NULL;

OpenTissueInstance::OpenTissueInstance()
{
    m_thread = new OpenTissueThread();
}

OpenTissueInstance::~OpenTissueInstance()
{

}

OpenTissueInstance *OpenTissueInstance::instance()
{
    if (_instance == NULL)
    {
        _instance = new OpenTissueInstance();
    }
    return _instance;
}

void OpenTissueInstance::convertCollisionObjToMeshType(std::string obj_file_name, void *collisionObjPtr)
{
    sdf_geometry_type  sdf_geom;

    mesh_type mesh;
    OpenTissue::mesh::obj_read( obj_file_name, mesh );
    OpenTissue::polymesh::triangulate(mesh);

    double edge_resolution = 1.0;
    bool face_sampling = false;
    OpenTissue::sdf::semiauto_init_geometry(mesh,edge_resolution,face_sampling,sdf_geom);//,64,false


    CollisionObjWrapper wrapper;
    wrapper.collisionObj = collisionObjPtr;
    wrapper.mesh = mesh;
    wrapper.sdfGeom = sdf_geom;
    m_collisionObjWrapperVector[collisionObjPtr] = wrapper;
}

void OpenTissueInstance::pushCommandConvert(std::string obj_file_name, void *collisionObjPtr)
{
    CommandConvertToMeshType commandConvert;
    commandConvert.obj_file_name = obj_file_name;
    commandConvert.collisionObjPtr = collisionObjPtr;
    m_commandConvertVector_Cache.push_back(commandConvert);
}

void OpenTissueInstance::pushCommandCollision(void *collisionObjPtr1, void *collisionObjPtr2)
{
    CommandComputeCollision commandCollision;
    commandCollision.collisionObjPtr1 = collisionObjPtr1;
    commandCollision.collisionObjPtr2 = collisionObjPtr2;
    m_commandCollisionVector.push_back(commandCollision);
}

void OpenTissueInstance::handleConvertCommand()
{
    m_commandConvertVector = m_commandConvertVector_Cache;
    int i=0;
    for(i = 0; i < m_commandConvertVector.size(); i++)
    {
        CommandConvertToMeshType command = m_commandConvertVector[i];
        convertCollisionObjToMeshType(command.obj_file_name, command.collisionObjPtr);
    }
    m_commandConvertVector.clear();
    m_commandConvertVector_Cache.clear();
}

void OpenTissueInstance::handleCollisionCommand()
{
    //put collision compute code:

}

void OpenTissueInstance::updateByThread()
{
    handleConvertCommand();
    handleCollisionCommand();
    //std::cout<<"OpenTissueInstance::updateByThread"<<std::endl;
}

void OpenTissueInstance::startThread()
{
    m_thread->start();
}
